package com.mushuilingfeng.ddd.user.domain.user.loginfilter;

import com.mushuilingfeng.ddd.framework.AsSpringBean;
import com.mushuilingfeng.ddd.framework.factory.DomainRepositoryFactory;
import com.mushuilingfeng.ddd.framework.factory.DomainServiceFactory;
import com.mushuilingfeng.ddd.user.domain.base.BusinessException;
import com.mushuilingfeng.ddd.user.domain.base.Ii8nCode;
import com.mushuilingfeng.ddd.user.domain.base.service.PropertyService;
import com.mushuilingfeng.ddd.user.domain.user.IUserLoginFilter;
import com.mushuilingfeng.ddd.user.domain.user.dto.AbstractLoginDto;
import com.mushuilingfeng.ddd.user.domain.user.entity.User;
import com.mushuilingfeng.ddd.user.domain.user.entity.UserLoginDevice;
import com.mushuilingfeng.ddd.user.domain.user.repository.IUserLoginDeviceRepository;

/**
 * 登陆设备过滤器
 *
 * @author 沐水淋风
 * @date 2024/10/3
 */
@AsSpringBean
public class LoginDeviceFilter implements IUserLoginFilter {
    
    @Override
    public int order() {
        return 2;
    }
    
    public int getMaxLoginDeviceCount() {
        String maxLoginDeviceCount = DomainServiceFactory.getDomainService(PropertyService.class).getProperty("user.login.maxLoginDeviceCount", "3");
        return Integer.parseInt(maxLoginDeviceCount);
    }
    
    @Override
    public void filter(User user, AbstractLoginDto loginParams) {
        IUserLoginDeviceRepository repository = DomainRepositoryFactory.getRepository(IUserLoginDeviceRepository.class);
        if (repository.getLoginDeviceCount(user.getId()) >= getMaxLoginDeviceCount()) {
            throw new BusinessException(Ii8nCode.LOGIN_DEVICE_LIMIT);
        }
        UserLoginDevice device = repository.getByUserIdAndDeviceCode(user.getId(), loginParams.getLoginDeviceCode());
        if (null == device) {
            UserLoginDevice loginDevice = new UserLoginDevice();
            loginDevice.setUserId(user.getId());
            loginDevice.setDeviceCode(loginParams.getLoginDeviceCode());
            loginDevice.setDeviceName(loginParams.getLoginDeviceName());
            loginDevice.saveNew();
        } else {
            device.updateLastLoginTime();
        }
    }
    
}
